//
//  ViewController.m
//  AndroidLock
//
//  Created by Purnama Santo on 11/2/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "DrawPatternLockViewController.h"
#import "DrawPatternLockView.h"

#define MATRIX_SIZE 3

@implementation DrawPatternLockViewController



@synthesize delegate;
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)loadView {
  [super loadView];
  
  self.view = [[DrawPatternLockView alloc] init];
}


- (void)viewDidLoad
{
  [super viewDidLoad];
    self.view = [[DrawPatternLockView alloc] init];
    if ([[NSUserDefaults standardUserDefaults]objectForKey:kNewPassword]||[[NSUserDefaults standardUserDefaults] boolForKey:kSetDecoyPassword] == YES||[[NSUserDefaults standardUserDefaults] boolForKey:kChangeDecoyPassword] == YES)
    {
        mPatternKey1=nil;
        mPatternKey2=nil;
        
    }
    else
    {
    mPatternKey1=[[NSUserDefaults standardUserDefaults] objectForKey:kPattern1];
    mPatternKey2=[[NSUserDefaults standardUserDefaults] objectForKey:kPattern2];
    }
    self.view.backgroundColor = [UIColor darkGrayColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:self action:@selector(goBack:)];
    
    self.navigationItem.hidesBackButton = YES;
    for (int i=0; i<MATRIX_SIZE; i++) {
        for (int j=0; j<MATRIX_SIZE; j++) {
            UIImage *dotImage = [UIImage imageNamed:@"dot_off.png"];
            UIImageView *imageView = [[UIImageView alloc] initWithImage:dotImage
                                                       highlightedImage:[UIImage imageNamed:@"dot_on.png"]];
            imageView.frame = CGRectMake(0, 0, dotImage.size.width, dotImage.size.height);
            imageView.userInteractionEnabled = YES;
            imageView.tag = j*MATRIX_SIZE + i + 1;
            [self.view addSubview:imageView];
        }
    }
}
-(void)viewDidDisappear:(BOOL)animated
{
    self.delegate = Nil;
//    if ([[NSUserDefaults standardUserDefaults] objectForKey:kNewPassword]) {
//        [NSUserDefaults standardUserDefaults]
//    }
}

- (void)viewWillLayoutSubviews {
  int w = self.view.frame.size.width/MATRIX_SIZE;
  int h = self.view.frame.size.height/MATRIX_SIZE;

  int i=0;
  for (UIView *view in self.view.subviews)
    if ([view isKindOfClass:[UIImageView class]]) {
      int x = w*(i/MATRIX_SIZE) + w/2;
      int y = h*(i%MATRIX_SIZE) + h/2;
      view.center = CGPointMake(x, y);
      i++;
    }

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
  if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
      return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
  } else {
      return YES;
  }
}


- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
  _paths = [[NSMutableArray alloc] init];
}



- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
  CGPoint pt = [[touches anyObject] locationInView:self.view];
  UIView *touched = [self.view hitTest:pt withEvent:event];
  
  DrawPatternLockView *v = (DrawPatternLockView*)self.view;
  [v drawLineFromLastDotTo:pt];

  if (touched!=self.view) {
    NSLog(@"touched view tag: %d ", touched.tag);
    
    BOOL found = NO;
    for (NSNumber *tag in _paths) {
      found = tag.integerValue==touched.tag;
      if (found)
        break;
    }
    
    if (found)
      return;
      
      if (touched.tag) {
          [_paths addObject:[NSNumber numberWithInt:touched.tag]];
          [v addDotView:touched];
      }
    
    

    UIImageView* iv = (UIImageView*)touched;
    iv.highlighted = YES;
  }

}


- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
  // clear up hilite
  DrawPatternLockView *v = (DrawPatternLockView*)self.view;
  [v clearDotViews];

  for (UIView *view in self.view.subviews)
    if ([view isKindOfClass:[UIImageView class]])
      [(UIImageView*)view setHighlighted:NO];
  
  [self.view setNeedsDisplay];
  
  // pass the output to target action...
  if (_target && _action)
  {
      NSLog(@"-------------%@ %@ %c %@",[[NSUserDefaults standardUserDefaults] objectForKey:kPattern],[[NSUserDefaults standardUserDefaults] objectForKey:@"NewPassword"],[[NSUserDefaults standardUserDefaults] boolForKey:kSetDecoyPassword],[[NSUserDefaults standardUserDefaults] objectForKey:kDecoyPassword]);
      if ([[NSUserDefaults standardUserDefaults] objectForKey:kPattern]==nil
          ||[[NSUserDefaults standardUserDefaults] objectForKey:@"NewPassword"]!=nil
          ||([[NSUserDefaults standardUserDefaults] boolForKey:kSetDecoyPassword] == YES && [[NSUserDefaults standardUserDefaults] objectForKey:kDecoyPassword] == nil) || [[NSUserDefaults standardUserDefaults] boolForKey:kChangeDecoyPassword] == YES)
      {
          
          if(mPatternKey1== nil)
          {
              [[NSUserDefaults standardUserDefaults] setObject:[self getKey] forKey:kPattern1];
              mPatternKey1=[[NSUserDefaults standardUserDefaults] objectForKey:kPattern1];
              UIAlertView *tAlertView = [[UIAlertView alloc] initWithTitle:@"Re-draw same pattern to save it" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
              [tAlertView show];
              
          }
          else if(mPatternKey2 == nil)
          {
              [[NSUserDefaults standardUserDefaults] setObject:[self getKey] forKey:kPattern2];
              mPatternKey2=[[NSUserDefaults standardUserDefaults] objectForKey:kPattern2];
              if ([mPatternKey1 isEqual:mPatternKey2])
              {
                  if ([[NSUserDefaults standardUserDefaults] boolForKey:kChangeDecoyPassword] == YES) {
                      
                      if ([[[NSUserDefaults standardUserDefaults] objectForKey:kPattern] isEqual:mPatternKey1]) {
                          [[NSUserDefaults standardUserDefaults] removeObjectForKey:kPattern1];
                          [[NSUserDefaults standardUserDefaults] removeObjectForKey:kPattern2];
                          mPatternKey1 = nil;
                          mPatternKey2 = nil;
                          
                          UIAlertView *talert = [[UIAlertView alloc] initWithTitle:@"Duplicate" message:@"Your Decoy password cannot be equal to Actual Password." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Retry", nil];
                          talert.tag = 2;
                          //            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kSetDecoyPassword];
                          [talert show];
                      }
                      else
                      {
                          [[NSUserDefaults standardUserDefaults] removeObjectForKey:kChangeDecoyPassword];
                      }
                      
                  }
                  else if ([[NSUserDefaults standardUserDefaults] boolForKey:kSetDecoyPassword])
                  {
                      if ([[[NSUserDefaults standardUserDefaults] objectForKey:kPattern] isEqual:mPatternKey1]) {
                          [[NSUserDefaults standardUserDefaults] removeObjectForKey:kPattern1];
                          [[NSUserDefaults standardUserDefaults] removeObjectForKey:kPattern2];
                          mPatternKey1 = nil;
                          mPatternKey2 = nil;
                          
                          UIAlertView *talert = [[UIAlertView alloc] initWithTitle:@"Duplicate" message:@"Your Decoy password cannot be equal to Actual Password." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Retry", nil];
                          talert.tag = 2;
                          //            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kSetDecoyPassword];
                          [talert show];
                      }
                      else
                      {
                          [[NSUserDefaults standardUserDefaults] removeObjectForKey:kSetDecoyPassword];
                      }
                  }
                  else if ([[NSUserDefaults standardUserDefaults] objectForKey:@"NewPassword"])
                  {
                      if ([mPatternKey1 isEqual:[[NSUserDefaults standardUserDefaults]objectForKey:kDecoyPassword]]) {
                          UIAlertView *talert = [[UIAlertView alloc] initWithTitle:@"InConsistency" message:@"Your Actual password cannot be equal to Decoy Password." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Retry", nil];
                          //                                  talert.tag = 2;
                          //            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kSetDecoyPassword];
                          [talert show];
                      }
                      else
                      {
                          [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"NewPassword"];
                          [[NSUserDefaults standardUserDefaults] removeObjectForKey:kPattern1];
                          [[NSUserDefaults standardUserDefaults] removeObjectForKey:kPattern2];
                      }
                  }
              }
              
              NSLog(@"--------pattern %@",[[NSUserDefaults standardUserDefaults] objectForKey:kPattern]);
              [_target performSelector:_action withObject:mPatternKey1 withObject:mPatternKey2];
          }
          else
          {
              UIAlertView *tAlertView = [[UIAlertView alloc] initWithTitle:@"Pattern Doesn't Not Match" message:nil delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:@"Retry", nil];
              tAlertView.delegate=self;
              tAlertView.tag=1;
              [tAlertView show];
          }
          
      }
      else
      {
          [_target performSelector:_action withObject:[self getKey]];
      }
      
  }
  
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if ([[alertView buttonTitleAtIndex:buttonIndex] isEqual:@"Cancel"]) {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:kPattern1];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:kPattern2];
        mPatternKey2=nil;
        mPatternKey1=nil;
        if ([[NSUserDefaults standardUserDefaults] boolForKey:kChangeDecoyPassword] == YES) {
            [[NSUserDefaults standardUserDefaults]removeObjectForKey:kChangeDecoyPassword ];
        }
        if (alertView.tag == 2) {
            if ([[NSUserDefaults standardUserDefaults] objectForKey:kSetDecoyPassword]) {
                [[NSUserDefaults standardUserDefaults]removeObjectForKey:kSetDecoyPassword];
            }
        }
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    else
    {
        mPatternKey2=nil;
        mPatternKey1=nil;

        [[NSUserDefaults standardUserDefaults] removeObjectForKey:kPattern2];
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:kPattern1];
    }
}

// get key from the pattern drawn
// replace this method with your own key-generation algorithm
- (NSString*)getKey {
  NSMutableString *key;
  key = [NSMutableString string];

  // simple way to generate a key
  for (NSNumber *tag in _paths) {
    [key appendFormat:@"%02d", tag.integerValue];
  }
  
  return key;
}

-(void)goBack:(id)sender
{
    if ([[NSUserDefaults standardUserDefaults] objectForKey:kPattern2]==Nil)
    {
        mPatternKey2=nil;
        mPatternKey1=nil;
        if ([[NSUserDefaults standardUserDefaults] objectForKey:@"NewPassword"])
        {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"NewPassword"];    
        }
        if ([[NSUserDefaults standardUserDefaults] objectForKey:kPattern1]) {
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:kPattern1];

        }
    }
    if ([[NSUserDefaults standardUserDefaults] objectForKey:kSetDecoyPassword]) {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:kSetDecoyPassword];
    }
    if ([[NSUserDefaults standardUserDefaults] objectForKey:kChangeDecoyPassword]) {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:kChangeDecoyPassword];
    }
    [self.navigationController popToRootViewControllerAnimated:YES];
}
- (void)setTarget:(id)target withAction:(SEL)action {
  _target = target;
  _action = action;
}

@end
